﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DOTNET_ASSIGNMENT.Models;
using DOTNET_ASSIGNMENT.Services;
using System.Web.UI;
using System.IO;
using PagedList;

using System.Windows.Forms;
using System.Threading;
namespace DOTNET_ASSIGNMENT.Controllers
{
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public class AccountController : Controller
    {

        public ActionResult Index()
        {
            if (Session["Email"] == null || String.IsNullOrEmpty(User.Identity.Name.ToString()))
            {
                FormsAuthentication.SignOut();
                return RedirectToAction("Login", "Account");
            }
            return View();
        }

        [HttpPost]
        public JsonResult IsEmailAvailable(string Email)
        {
            DataContext db = new DataContext();
            bool isAvailable = db.Customers.Any(e => e.Email.Equals(Email));
            return Json(!isAvailable, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(Customer customer)
        {
            CustomerServices customerServices = new CustomerServices();
            if (ModelState.IsValid)
            {
                if (customerServices.AddCustomer(customer))
                {
                    var path = "~/App_Data/Uploads/" + customer.Email;
                    var folder = Server.MapPath(path);

                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    return RedirectToAction("Login", "Account");
                }
                else
                {
                    ModelState.AddModelError("", "Register data is wrong!");
                }
            }

            return View(customer);
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(Customer customer)
        {
            try
            {
                if (customer.Email == "Admin@057213.com" && customer.Password == "Admin123")
                {
                    Session["Email"] = "Admin@057213.com";
                    return RedirectToAction("Index", "Home");
                }

                CustomerServices customerServices = new CustomerServices();
                var cus = customerServices.IsValid(customer.Email, customer.Password);
                if (cus != null)
                {
                    if (!cus.IsBlocked)
                    {
                        Session["Email"] = customer.Email;
                        FormsAuthentication.SetAuthCookie(customer.Email, false);
                        return RedirectToAction("Manage", "Account");
                    }
                    else
                    {
                        ModelState.AddModelError("", "your account is banned!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return View(customer);
        }

        public ActionResult Logout()
        {
            Session.RemoveAll();
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }


        //public ActionResult AsyncUpload()
        //{
        //    return View();
        //}

        [HttpGet]
        [ActionName("Manage")]
        public ActionResult Manage_Get(string sortOrder, string currentFilter, string searchString, int? page)
        {
            if (Session["Email"] == null || String.IsNullOrEmpty(User.Identity.Name.ToString()))
            {
                FormsAuthentication.SignOut();
                Session.RemoveAll();
                return RedirectToAction("Login", "Account");
            }

            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "email_desc" : "Email";
            ViewBag.BlockSortParm = sortOrder == "Blocked" ? "blocked_desc" : "Blocked";
            ViewBag.SizeSortParm = sortOrder == "Size" ? "size_desc" : "Size";

            FileServices fileServices = new FileServices();
            string email = User.Identity.Name.ToString();
            IEnumerable<DOTNET_ASSIGNMENT.Models.File> query = fileServices.GetFiles(email);

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            if (!String.IsNullOrEmpty(searchString))
            {
                query = query.Where(s => s.DisplayName.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "Size":
                    query = query.OrderBy(s => s.Size);
                    break;
                case "size_desc":
                    query = query.OrderByDescending(s => s.Size);
                    break;
                case "Blocked":
                    query = query.OrderBy(s => s.IsBlocked);
                    break;
                case "blocked_desc":
                    query = query.OrderByDescending(s => s.IsBlocked);
                    break;
                case "name_desc":
                    query = query.OrderByDescending(s => s.DisplayName);
                    break;
                case "Date":
                    query = query.OrderBy(s => s.Date);
                    break;
                case "date_desc":
                    query = query.OrderByDescending(s => s.Date);
                    break;
                case "email_desc":
                    query = query.OrderByDescending(s => s.CustomerEmail);
                    break;
                case "Email":
                    query = query.OrderBy(s => s.CustomerEmail);
                    break;
                default:
                    query = query.OrderBy(s => s.DisplayName);
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);
            return View(query.ToPagedList(pageNumber, pageSize));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("Manage")]
        public ActionResult Manage_Post(IEnumerable<HttpPostedFileBase> files)
        {
            //const int maxFileLength = 512000; //500KB = 500 * 1024
            FileServices fileServices = new FileServices();
            DOTNET_ASSIGNMENT.Models.File f = new DOTNET_ASSIGNMENT.Models.File();
            string email = User.Identity.Name.ToString();
            IEnumerable<DOTNET_ASSIGNMENT.Models.File> query = fileServices.GetFiles(email);

            int count = 0;
            //try
            //{
            if (files != null)
            {
                foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        if (file.FileName != "")
                        {
                            var originalFilename = Path.GetFileNameWithoutExtension(file.FileName);
                            var extension = Path.GetExtension(file.FileName);
                            string name = fileServices.ChangeFileName(Session["Email"].ToString(), originalFilename);

                            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads/" + Session["Email"].ToString()), name + "." + extension);
                            file.SaveAs(path);

                            var urlCrypto = Request.Url.GetLeftPart(UriPartial.Authority)+ "/" +
                               DateTime.Now.Minute + DateTime.Now.Second + Guid.NewGuid().ToString() + DateTime.Now.DayOfYear;
                            f.CustomerEmail = Session["Email"].ToString();
                            f.Extension = extension;
                            f.DisplayName = name;
                            f.URL = urlCrypto;
                            f.Size = (file.ContentLength / 1024).ToString() + " KB";
                            f.Date = DateTime.Now.ToString();
                            fileServices.AddFile(f);
                            ++count;
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "File is not attached!");
                    }
                }
            }
            return new JsonResult { Data = "Successfully " + count + " file(s) uploaded" };
        }

        [HttpPost]
        public ActionResult DeleteFile(string name)
        {

            FileServices fileServices = new FileServices();

            var databaseFile = fileServices.GetFile(Session["Email"].ToString(), name);
            if (databaseFile == null) return RedirectToAction("Manage", "Account");

            var filename = databaseFile.DisplayName + "." + databaseFile.Extension;
            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads/" + Session["Email"].ToString()), filename);

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
            fileServices.DeleteFile(Session["Email"].ToString(), name);

            return RedirectToAction("Manage");
        }

        public ActionResult Download(string imageName)
        {
            FileServices fileServices = new FileServices();

            var databaseFile = fileServices.GetFile(Session["Email"].ToString(), imageName);
            if (databaseFile == null) return RedirectToAction("Manage", "Account");

            var name = databaseFile.DisplayName + "." + databaseFile.Extension;
            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads/" + Session["Email"].ToString()), name);

            if (System.IO.File.Exists(path))
            {
                var file = File(path, System.Net.Mime.MediaTypeNames.Application.Octet, name);
                var urlencode= HttpUtility.UrlEncode(file.FileName);
                //MessageBox.Show(Request.Url.GetLeftPart(UriPartial.Authority));
                
                return file;
            }         
            return RedirectToAction("Manage", "Account");
        }

        public ApartmentState ApartmentState { get; set; }
        private static string _Val;
        public static string Val
        {
            get { return _Val; }
            set { _Val = value; }
        }

        public static void myMethod()
        {
            System.Windows.Forms.Clipboard.SetText(Val);
        }

        public ActionResult Share(string imageName)
        {

                FileServices fileServices = new FileServices();

                var databaseFile = fileServices.GetFile(Session["Email"].ToString(), imageName);

                if (databaseFile != null)
                {

                    TempData["AlertMessage"] = databaseFile.URL;
                    Val = databaseFile.URL;
                    Thread newThread = new Thread(new ThreadStart(myMethod));
                    newThread.SetApartmentState(ApartmentState.STA);
                    newThread.Start();
                    return RedirectToAction("Manage", "Account");
                }
                else
                {
                    TempData["AlertMessage"] = "Could not find this file! Try again or Contact with us";
                    return RedirectToAction("Manage", "Account");
                }
        }
     
        [HttpGet]
        public ActionResult Setting()
        {
            if (Session["Email"] == null)
            {
                FormsAuthentication.SignOut();
                return RedirectToAction("Login", "Account");
            }

            string email = Session["Email"].ToString();
            //MessageBox.Show(email);
            var cus = new CustomerServices().GetCustomer(email);
            if (cus == null) return RedirectToAction("Login", "Account");

            return View(cus);
        }

        public ActionResult Setting(Customer customer)
        {
            try
            {
                CustomerServices customerServices = new CustomerServices();
                if (customerServices.Edit(customer))
                {
                    return RedirectToAction("Manage", "Account");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return View(customer);
        }

    }
}
